package com.d2.pay.handler;

import com.alibaba.fastjson.JSON;
import com.d2.pay.model.D2Client;
import com.d2.pay.model.payjs.Order;
import com.d2.pay.netty.NettySession;
import com.d2.pay.rest.PayJsController;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;


@Component
public class ServerHandler extends ChannelInboundHandlerAdapter {
    // socket 断开方式
    //https://blog.csdn.net/weixin_30624825/article/details/101253747?depth_1-utm_source=distribute.pc_relevant.none-task&utm_source=distribute.pc_relevant.none-task

//    sysctl.conf文件里面设置：
//
//    net.ipv4.tcp_keepalive_time = 10
//
//    net.ipv4.tcp_keepalive_probes = 2
//
//    net.ipv4.tcp_keepalive_intvl = 2

    private ApplicationContext applicationContext;



    public ServerHandler(ApplicationContext applicationContext){
        this.applicationContext = applicationContext;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("接收到客户端信息:" + msg.toString());

        D2Client d2Client =  JSON.parseObject(msg.toString(),D2Client.class);
        PayJsController payJsController = (PayJsController) applicationContext.getBean("payJsController");

        if (d2Client.getAction().equals("order")){
            Order order = JSON.parseObject(d2Client.getPayload(),Order.class);
            System.err.println(order.getMoney());
            System.err.println(order.getBody());
            String url = payJsController.nativePay(order.getMoney(),order.getBody());
            if (url == null || url.equals(""))
                ctx.channel().writeAndFlush("404");

            ctx.channel().writeAndFlush(url);
        }else {
            ctx.channel().writeAndFlush("404");
        }
    }


    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
//        NettySession.removeSession("1");
        ctx.close();
    }

    //客户端去和服务端连接成功时触发
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端链接");
//        ctx.writeAndFlush("hello client");
//        NettySession.addSession("1",ctx.channel());
        ctx.fireChannelActive();
    }

}